/**
 * create by zhangpu
 * date:2015年3月4日
 */
package com.acooly.module.openapi.client.provider.newyl.signature;

import com.acooly.module.openapi.client.provider.newyl.enums.NewYlSignTypeEnum;
import com.acooly.module.openapi.client.provider.newyl.support.NewYlKeyStoreInfo;
import com.acooly.module.safety.signature.AbstractSigner;

import org.springframework.stereotype.Component;

import java.security.PublicKey;
import java.security.Signature;

/**
 * @author zhangpu
 */
@Component("newYlKeyStoreSigner")
public class NewYlKeyStoreSigner extends AbstractSigner<String, NewYlKeyStoreInfo> {


    @Override
    protected String getWaitToSigin(String plain) {
        return plain;
    }

    @Override
    protected void doVerify(String waitForSign, NewYlKeyStoreInfo key, String sign) {
        try {
            PublicKey publicKey = key.loadKeys().getPublicKey();
            Signature signature = Signature.getInstance(key.getSignatureAlgo());
            signature.initVerify(publicKey);
            signature.update(waitForSign.getBytes(key.getPlainEncode()));
            boolean result = signature.verify(key.getSignatureCodec().decode(sign));
            if (!result) {
                throw new RuntimeException("签名未通过");
            }
        } catch (RuntimeException re) {
            throw re;
        } catch (Exception e) {
            throw new RuntimeException("证书验签失败:" + e.getMessage());
        }
    }

    @Override
    protected String doSign(String waitToSignStr, NewYlKeyStoreInfo key) {
        try {
            Signature signature = Signature.getInstance(key.getSignatureAlgo());
            signature.initSign(key.loadKeys().getPrivateKey());
            signature.update(waitToSignStr.getBytes(key.getPlainEncode()));
            byte[] sign = signature.sign();
            return key.getSignatureCodec().encode(sign).replaceAll("(\r\n|\r|\n|\n\r)", "");
        } catch (Exception e) {
            throw new RuntimeException("证书签名失败:" + e.getMessage());
        }
    }

    @Override
    public String getSinType() {
        return NewYlSignTypeEnum.YlRsa.name();
    }


}
